$(document).ready(function () {

    initSubMenu();
    queryTable();


    layui.use(function () {

        var layer = layui.layer;

        // 表格
        form = layui.form;
        laydate = layui.laydate;
        form.on('select(formSelect)', function (data) {//监听下拉框条件下拉
            $('div[lay-filter="search"]').click();
        });

        form.on('submit(search)', function (data) {//监听查询提交
            params = data.field;
            params.pageSize = 10;
            queryTable()
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });


        form.on('submit(edit)', function (data) {//监听新增修改提交

            let msgType = "";
            if (curId) {
                msgType = "编辑"
                data.field.id = curId
            } else {
                msgType = "新增"
            }

            formData = new FormData();

            //将有值的参数放入formdata
            for (var key in data.field) {
                if (data.field.hasOwnProperty(key)) {
                    formData.append(key, data.field[key]);
                }
            }
            //判断是否传入照片
            if (file) {//如果存在文件,说明是编辑并且修改了照片
                formData.append('photo', file)
            } else {
                if (photoUuid) {
                    formData.append('photoUuid', photoUuid);
                }
            }


            ajaxUploadFile('/person/save', upLoadCallBack, formData)
            function upLoadCallBack(res) {
                if (res.message == "OK") {
                    layer.close(drawer);
                    layer.msg(msgType + '成功', { icon: 1, time: 2000 });
                    file = null;
                    queryTable()
                } else {
                    layer.msg(msgType + '失败', { icon: 2, time: 2000 });
                    file = null;
                }
            }



            return false;
        });


    });
})
var params = {};//查询条件参数
var form, unit, laydate;
var drawer;//抽屉实例
var curId = null;//当前选中物资ID
var file = null, photoUuid = null;


queryTable = () => {

    let toolWidth = window.innerWidth / 1920 * 240
    layui.use('table', function () {
        var table = layui.table;
        //展示已知数据
        table.render({
            elem: '#table'
            , text: {
                none: '暂无数据'
            }
            , method: 'POST'
            , url: ajaxPrefix() + "/person/mulit/list"
            , headers: {
                SessionId: JSON.parse(localStorage.getItem('sessionId'))
            }
            , contentType: 'application/json'
            , where: params
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.result.total, //解析数据长度
                    "data": res.result.data //解析数据列表
                };
            }
            , request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                ,
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , cols: [[ //标题栏
                {
                    field: 'photoPath', title: '', align: "center"
                    , templet: function (d) {

                        if (d.photoPath) {
                            return `<img title="查看" onclick=showPhoto("${d.photoPath}") src="/images/${d.photoPath}"
                              style="width: 0.4rem;height: 0.4rem;cursor: pointer;">`
                        } else {
                            return `<img title="暂未上传" onclick=showPhoto() src="../static/img/photo.png"
                             style="width: 0.4rem;height: 0.4rem;cursor: pointer;">`
                        }
                    },
                }
                , { field: 'name', title: '姓名', align: "center" }
                , { field: 'professionalTitleDesc', title: '消防救援衔', align: "center" }
                , { field: 'cellphone', title: '联系方式', align: "center" }
                , {
                    field: 'unit', title: '年龄', align: "center"
                    , templet: function (d) {

                        if (d.birthDate != '' && d.birthDate) {
                            return $.calculateAge(d.birthDate);
                        } else {
                            return ''
                        }
                    },
                }
                , { field: 'postDesc', title: '职务', align: "center" }
                , { field: 'positionalPositionDesc', title: '专业岗位', align: "center" }
                , { field: 'workDate', title: '入职时间', align: "center" }
                , { field: 'rfidName', title: 'rfid号', align: "center" }
                , {
                    flex: 'right',
                    title: '操作',
                    align: 'center',
                    width: toolWidth,
                    templet: function (d) {
                        let res = JSON.stringify(d);
                        return `<div class="table-tool">
                                    <div onclick='tableHandle(1,${res})' class="table-edit layui-btn">
                                    <img src="../static/img/edit.png">个人信息
                                    </div>
                                    <div onclick='tableHandle(2,${res})' class="table-del layui-btn">
                                    <img src="../static/img/del.png">删除
                                    </div>
                                </div>`;
                    },
                },
            ]]
            , height: 'full'
            // ,skin: 'line' //表格风格
            , even: true
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                , groups: 3 //只显示 1 个连续页码
                , first: false //不显示首页
                , last: false //不显示尾页

            }
            , done: function (res, curr, count) {

                $('.layui-table-cell').height($('.contain-table-list').height() / 20);
            },

        });

    });
}


// 列表功能按钮操作
tableHandle = (type, res) => {
    switch (type) {
        case 1://编辑
            curId = res.id
            photoUuid = res.photoUuid;
            openDrawer(2, res)
            if (res.photoPath) {
                $('.m').html(`<img id="img" src="/images/${res.photoPath}" style="max-height: 100%;"/>`)
            }
            break;
        case 2://删除

            layer.confirm('确定删除该记录吗？', { icon: 3 }, function () {

                new AjaxChain()
                    .setUrl('/person/delete')
                    .setData({ id: res.id })
                    .then(data => {
                        layer.msg('删除成功', { icon: 1, time: 1500 });
                        queryTable();
                    })
                    .catch(err => {
                        console.error('请求异常:', err);
                    })
                    .send();
            });
            break;

        case 3://新增 
            curId = null;
            photoUuid = null;
            openDrawer(1)
            break;


        default:
            break;
    }
}



openDrawer = (type, res) => {
    drawer = layer.open({
        title: (type == 1 ? "新增" : "编辑") + '消防员',
        type: 1,
        maxmin: true,
        offset: 'r',
        anim: 'slideLeft', // 从右往左
        area: ['60%', '100%'],
        shade: 0.3,
        shadeClose: false,
        id: 'edit-offset',
        success: function (layero, index, that) {

            laydate.render({
                elem: '.laydate-item',
                disabledDate: function (date, type) {
                    return date.getTime() > Date.now();
                }
            });
            laydate.render({
                elem: '#politicalTime',
                type: 'month'
            });

            document.getElementById('upload-input').value = '';

            if (res) {
                form.val('editForm', res);

            } else {
                form.render(null, 'editForm');
            }
        },
        content: $('#add-temp').html()
    });

}


document.querySelector("#upload-input").onchange = function () {
    let z = new zz();
    z.compressPhotoUpload({
        elem: this,		//必传，上传图片的input元素
        ratio: 0.5,		//默认为0.1   压缩比
        maxsize: 100,	//默认为1024,单位为kb    大于此值则做压缩操作
        success: (e) => {

            if (e.size > 512 * 1024) {
                layer.msg('照片超出大小限制', { icon: 2, time: 1500 });
            } else {
                $('.m').html(`<img id="img" src="${e.data}" style="max-height: 100%;"/>`)

                // 从Base64字符串中移除前缀（如"data:image/jpeg;base64,"）
                var base64Data = e.data.split(',')[1];

                // 将Base64字符串解码为二进制数据
                var byteCharacters = atob(base64Data);

                // 创建一个数组来存储二进制数据
                var byteNumbers = new Array(byteCharacters.length);
                for (var i = 0; i < byteCharacters.length; i++) {
                    byteNumbers[i] = byteCharacters.charCodeAt(i);
                }

                // 将字节数组转换为ArrayBuffer
                var byteArray = new Uint8Array(byteNumbers);

                // 创建Blob对象
                var blob = new Blob([byteArray], { type: 'image/jpeg' }); // 这里需要根据实际文件类型设置

                // 使用Blob对象创建File对象
                file = new File([blob], "人像识别" + Date.now() + '.jpg', { type: 'image/jpeg' });

            }
        }
    });
}
